package com.podium.auth.handle;

import com.alibaba.fastjson2.JSON;
import com.podium.auth.utils.ServletUtils;
import com.podium.comment.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 *认证失败处理类 返回未授权
 *
 * @author swz
 * @date 2022/11/02
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        try {
            String msg = "请求访问：" + request.getRequestURI() + "，认证失败，无法访问系统资源";
            ServletUtils.sendResponse(response, JSON.toJSONString(new AjaxResult<Void>(HttpStatus.UNAUTHORIZED.value(), msg)));
            // 记录日志
            logger.warn("{} {}", msg, authException.getMessage());
        } catch (Exception e) {
            // 捕获异常并记录日志
            logger.error("处理认证失败响应时发生错误", e);
            ServletUtils.sendResponse(response, JSON.toJSONString(new AjaxResult<Void>(500, "系统异常，请联系管理员！")));
        }
    }


}
